<template>
  <div class="files_preview">
    <div class="f_v_t">
      <div class="f_v_t_right">
        <el-select class="my_el_select" v-model="fileTypeSel">
          <el-option label="全部" :value="0"></el-option>
          <el-option label="我发送的" :value="1"></el-option>
          <el-option label="我接收的" :value="2"></el-option>
        </el-select>
        <!-- <div class="f_update" @click.stop.prevent="searchFile()">
                    <img src="static/image/home/update.png" />
                </div> -->
      </div>
      <div class="f_v_t_left">
        <div class="f_s_w">
          <div class="f_s_icon"></div>
          <input type="text" v-model="files_search" placeholder="搜索文件">
          <img v-show="files_search.trim()!=''" @click.stop.prevent="files_search=''" src="static/image/home/clear_icon.png">
        </div>
        <el-date-picker class="my_el_select my_el_select_time" v-model="exTime" type="daterange" align="right" unlink-panels value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" :picker-options="$store.state.pickerOptions">
        </el-date-picker>
      </div>
      <div class="f_btn_w" v-show="checkFileArray.length>0" style="margin-top:2px">
        <el-button type="info" size="mini" @click.stop.prevent="forwardingSet" style="margin-left:10px">转发({{checkFileArray.length}}/9)</el-button>
        <el-button type="info" size="mini" plain @click.stop.prevent="checkCancel">取消</el-button>
      </div>
    </div>
    <div class="f_v_main">
      <template v-for="(item,index) in files_list">
        <div class="files_item" :key="'file_'+item.messageId">
          <div class="f_tiem_m" @click.stop.prevent='setChoose(item,index)'>
            <span class='checkSpan' :class='{chooseSpan:item.isChoose,active:item.isChoose}'></span>
            <div class="f_t_icon">
              <img v-lazy="$utilJs.getFileType(item.value)">
            </div>
            <div class="file_info">
              <div class="file_name">{{item.value | interception}}</div>
              <div>{{item.duration | convertByte}}&nbsp;|&nbsp;{{item.time | timeFormat}}&nbsp;{{item.sendId==myInfo.id?myInfo.name:item.name}}</div>
            </div>
            <div class="files_set">
              <Tooltip content="转发" placement="bottom">
                <span class="f_sd" @click.stop.prevent='toForwarding(item)'></span>
              </Tooltip>
              <Tooltip content="下载" placement="bottom" v-if="item.isDownLoad=='0'">
                <span class="f_dl" @click.stop.prevent='toDownFile(item)'></span>
              </Tooltip>
              <Tooltip content="打开" placement="bottom" v-if="item.isDownLoad!='0'&&item.isDownLoad!='loading'">
                <span class="f_op" @click.stop.prevent='toPreviewFile(item)'></span>
              </Tooltip>
            </div>
          </div>
          <div class="file_pg">
            <Progress v-if="item.upload==1" :percent="item.progress?item.progress:0" status="active"></Progress>
          </div>
        </div>
      </template>
    </div>
    <div class="page_box" v-show="filesCount.length>pageSize">
      <Page class="page_main" :total="filesCount.length" show-total :current="files_cur" :page-size='pageSize' @on-change='pageChange'></Page>
      <div class="page_foot page_foot_examine">
        <div>跳转至</div><input type="number" min="1" v-model="page_num">页&nbsp;<button @click.stop.prevent='goPage'>确定</button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "filesExamine",
  props: {
    toInfo: {
      type: Object,
      default: () => {
        return {
          id: "",
          name: "",
          isGroup: false,
        };
      },
    },
    files_show: {
      type: Boolean,
      default: false,
    },
    isShow: {
      type: Boolean,
      default: false,
    },
    isResetFiles: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      fileTypeSel: 0,
      datepickerOptions: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
      files_list: [],
      filesCount: [],
      files_search: "",
      files_cur: 0, //文件当前页数
      pageSize: 10, //每页显示条数
      page_num: 1,
      exTime: null, //消息搜索开始时间
      checkFileArray: [],
      pickerOptionsStart: {
        disabledDate: (time) => {
          if (this.end_time) {
            return time.getTime() > new Date(this.end_time).getTime();
          }
        },
      },
      pickerOptionsEnd: {
        disabledDate: (time) => {
          if (this.start_time) {
            return time.getTime() < new Date(this.start_time).getTime();
          }
        },
      },
    };
  },
  computed: {
    ...mapState(["myInfo", "ws"]),
    tableId() {
      return this.myInfo.id;
    },
    sqlTable() {
      return {
        userHotKey: `user_hot_key`,
        uninterruptedList: `uninterrupted_list_${this.tableId}`, //免打扰列表
        userInformation: `user_information_${this.tableId}`, //用户信息表
        sessionList: `session_list_${this.tableId}`, //会话列表
        broadcastList: `broadcast_list_${this.tableId}`, //广播列表
        publicList: `public_list_${this.tableId}`, //公众号列表
        groupList: `group_list_${this.tableId}`, //群列表
        messageList: `message_list_${this.tableId}`, //群聊消息表
        privateList: `private_list_${this.tableId}`, //单聊消息表
        publicRecords: `public_records_${this.tableId}`, //公众号记录表
        groupUsers: `group_users_${this.tableId}`, //	groupMessageEnity: 'GroupMessageEnity_' + this.myInfo.id,
        systemTable: `system_${this.tableId}`,
      };
    },
  },
  filters: {
    Interception(value) {
      let index = value.lastIndexOf("/");
      let str = value.substring(index + 1, value.length);
      return str;
    },
    convertByte(byteCount) {
      var count = parseFloat(byteCount),
        unitArr = ["b", "Kb", "Mb", "Gb", "Tb"],
        index = 0;
      if (!count) return 0;
      for (let i = 0; i < 5; i++) {
        if (count >= 1024) {
          count = count / 1024;
          index++;
        } else {
          return index > 0
            ? count.toFixed(2) + unitArr[index]
            : count + unitArr[index];
        }
        if (index == 4) {
          return count.toFixed(2) + unitArr[index];
        }
      }
    },
  },
  methods: {
    checkCancel() {
      this.checkFileArray = [];
      for (let i = 0; i < this.files_list.length; i++) {
        this.$set(this.files_list[i], "isChoose", false);
      }
    },
    forwardingSet() {
      console.log("转发的文件", this.checkFileArray);
      this.$emit("forwardingSet", this.checkFileArray);
    },
    //移出文件
    delCheckFile(id) {
      for (let i = 0; i < this.checkFileArray.length; i++) {
        this.checkFileArray[i].messageId == id &&
          this.checkFileArray.splice(i, 1);
      }
    },
    //多选
    setChoose(item, index) {
      let result = !item.isChoose;
      if (this.checkFileArray.length >= 9 && result) {
        this.$Message.info("超过所选文件上限");
        return;
      }
      this.$set(item, "isChoose", result);
      if (result) {
        this.checkFileArray.push(item);
      } else {
        this.delCheckFile(item.messageId);
      }
      console.log(item, "选择文件");
    },
    toDownFile(temp) {
      this.$emit("toDownFile", temp);
    },
    toForwarding(temp) {
      this.$emit("toForwarding", temp);
    },
    //文件预览
    toPreviewFile(item) {
      let _this = this;
      console.log(item, "文件预览");
      let rep = this.$shell("OpenFlieByUrl", [
        this.$isRelativePath(item.isDownLoad),
      ]);
      rep = JSON.parse(rep);
      console.log(rep, "文件预览");
      if (rep.return_code == "FALSE") {
        this.$Message.info("系统找不到指定的文件,请重新下载");
        this.$set(item, "isDownLoad", 0);
        return;
      }
    },
    goPage() {
      let maxPage = Math.ceil(this.filesCount.length / this.pageSize);
      if (this.page_num > maxPage || this.page_num < 1) {
        this.$Message.warning("请输入正确页数");
        return;
      }
      this.files_cur = parseInt(this.page_num);
      this.$forceUpdate();
    },
    pageChange(index) {
      this.files_cur = index;
      console.log(index, "页数");
    },
    operationalDatabase(statements, index) {
      let to = JSON.stringify({
        Sqlstr: statements,
      });
      return arguments[1]
        ? JSON.parse(this.$shellSQL(to, index))
        : JSON.parse(this.$shellSQL(to));
    },
    searchFile(value) {
      console.log(value, this.fileTypeSel, "当前查询条件");
      let ct1 = "",
        ct2 = "";
      if (this.exTime) {
        ct1 = new Date(this.exTime[0]).getTime();
        ct2 = new Date(this.exTime[1]).getTime();
      }
      this.files_list = [];
      this.files_cur = 0;
      var prstr;
      var grstr;
      if (value) {
        if (this.fileTypeSel == 0) {
          prstr = `${
            this.sqlTable.privateList
          } WHERE value LIKE '%${value}%' AND value NOT LIKE '%UserFiles%' AND type='file' AND (time>='${
            ct1 ? Number(ct1) : 0
          }' AND time<='${ct2 ? Number(ct2) : new Date().getTime()}')`;
          grstr = `${
            this.sqlTable.messageList
          } WHERE value LIKE '%${value}%' AND value NOT LIKE '%UserFiles%' AND type='file' AND (time>='${
            ct1 ? Number(ct1) : 0
          }' AND time<='${ct2 ? Number(ct2) : new Date().getTime()}')`;
        } else if (this.fileTypeSel == 1) {
          prstr = `${
            this.sqlTable.privateList
          } WHERE value LIKE '%${value}%' AND value NOT LIKE '%UserFiles%' AND type='file' AND sendId='${
            this.myInfo.id
          }' AND (time>='${ct1 ? Number(ct1) : 0}' AND time<='${
            ct2 ? Number(ct2) : new Date().getTime()
          }')`;
          grstr = `${
            this.sqlTable.messageList
          } WHERE value LIKE '%${value}%' AND value NOT LIKE '%UserFiles%' AND type='file' AND sendId='${
            this.myInfo.id
          }' AND (time>='${ct1 ? Number(ct1) : 0}' AND time<='${
            ct2 ? Number(ct2) : new Date().getTime()
          }')`;
        } else if (this.fileTypeSel == 2) {
          prstr = `${
            this.sqlTable.privateList
          } WHERE value LIKE '%${value}%' AND value NOT LIKE '%UserFiles%' AND type='file' AND receiveId='${
            this.myInfo.id
          }' AND (time>='${ct1 ? Number(ct1) : 0}' AND time<='${
            ct2 ? Number(ct2) : new Date().getTime()
          }')`;
          // grstr =`${this.sqlTable.messageList} WHERE value LIKE '%${value}%' AND type='file' AND receiveId='${this.myInfo.id}' AND (time>='${ct1?Number(ct1):0}' AND time<='${ct2?Number(ct2):new Date().getTime()}')`;
          // 群里接收文件接收人的ID全部是群ID 所以只要发送人不是自己 就全部是接收的文件
          grstr = `${
            this.sqlTable.messageList
          } WHERE value LIKE '%${value}%' AND value NOT LIKE '%UserFiles%' AND type='file' AND sendId!='${
            this.myInfo.id
          }' AND (time>='${ct1 ? Number(ct1) : 0}' AND time<='${
            ct2 ? Number(ct2) : new Date().getTime()
          }')`;
        }
      } else {
        if (this.fileTypeSel == 0) {
          prstr = `${this.sqlTable.privateList} WHERE type='file' AND (time>='${
            ct1 ? Number(ct1) : 0
          }' AND time<='${ct2 ? Number(ct2) : new Date().getTime()}')`;
          grstr = `${this.sqlTable.messageList} WHERE type='file' AND (time>='${
            ct1 ? Number(ct1) : 0
          }' AND time<='${ct2 ? Number(ct2) : new Date().getTime()}')`;
        } else if (this.fileTypeSel == 1) {
          prstr = `${this.sqlTable.privateList} WHERE type='file' AND sendId='${
            this.myInfo.id
          }' AND (time>='${ct1 ? Number(ct1) : 0}' AND time<='${
            ct2 ? Number(ct2) : new Date().getTime()
          }')`;
          grstr = `${this.sqlTable.messageList} WHERE type='file' AND sendId='${
            this.myInfo.id
          }' AND (time>='${ct1 ? Number(ct1) : 0}' AND time<='${
            ct2 ? Number(ct2) : new Date().getTime()
          }')`;
        } else if (this.fileTypeSel == 2) {
          prstr = `${
            this.sqlTable.privateList
          } WHERE type='file' AND receiveId='${this.myInfo.id}' AND (time>='${
            ct1 ? Number(ct1) : 0
          }' AND time<='${ct2 ? Number(ct2) : new Date().getTime()}')`;
          // grstr =`${this.sqlTable.messageList} WHERE type='file' AND receiveId='${this.myInfo.id}' AND (time>='${ct1?Number(ct1):0}' AND time<='${ct2?Number(ct2):new Date().getTime()}')`;
          // 群里接收文件接收人的ID全部是群ID 所以只要发送人不是自己 就全部是接收的文件
          grstr = `${
            this.sqlTable.messageList
          } WHERE type='file' AND sendId!='${this.myInfo.id}' AND (time>='${
            ct1 ? Number(ct1) : 0
          }' AND time<='${ct2 ? Number(ct2) : new Date().getTime()}')`;
        }
      }
      let prRes = this.operationalDatabase(
        `SELECT * FROM  ${prstr} ORDER BY time DESC;`,
        1
      ); //limit 20
      let grRes = this.operationalDatabase(
        `SELECT * FROM  ${grstr} ORDER BY time DESC;`,
        1
      );
      console.log(prRes, "搜索文件列表", grRes);
      // 新增去除文件发送失败的列，为isDownLoad==404
      this.filesCount = []
        .concat(prRes.list, grRes.list)
        .filter((item) => item.isDownLoad != "404");
      console.log(this.filesCount, "filesCount");
      this.files_cur = 1;
      this.$forceUpdate();
    },
  },
  watch: {
    isResetFiles() {
      //发送完成重置多选
      if (this.isResetFiles) {
        this.checkCancel();
      }
    },
    isShow: {
      handler(val, oval) {
        if (val) {
          this.searchFile();
        }
        console.log(this.isShow, "ISSHOW");
      },
      deep: true,
    },
    files_cur: {
      handler(val, oval) {
        let starIndex = (val - 1) * this.pageSize;
        let endIndex = val * this.pageSize;
        this.files_list = this.filesCount.slice(starIndex, endIndex);
        if (this.checkFileArray.length > 0) {
          for (let i = 0; i < this.files_list.length; i++) {
            for (let j = 0; j < this.checkFileArray.length; j++) {
              if (
                this.files_list[i].messageId == this.checkFileArray[j].messageId
              ) {
                this.$set(this.files_list[i], "isChoose", true);
              }
            }
          }
        }
        console.log(starIndex, endIndex, "index", this.files_list);
      },
      deep: true,
    },
    page_num() {
      //   if (this.filesCount.length <= 0) {
      //     this.page_num = 1;
      //     return;
      //   }
      //   let maxcount = Math.ceil(this.filesCount.length / this.pageSize);
      //   if (this.page_num >= maxcount) {
      //     this.page_num = parseInt(maxcount);
      //   } else if (this.page_num <= 0) {
      //     this.page_num = 1;
      //   } else {
      //     this.page_num = parseInt(this.page_num);
      //   }
    },
    files_search() {
      if (this.files_search.trim() == "") {
        this.searchFile();
      } else {
        this.searchFile(this.files_search);
      }
    },
    fileTypeSel() {
      this.searchFile();
    },
    exTime: {
      handler(newValue, oldValue) {
        this.searchFile();
      },
    },
  },
};
</script>
<style scoped>
.my_el_select {
  width: 120px;
}
.f_v_t_right {
  margin-right: 10px;
}
.my_el_select_time {
  margin-left: 10px;
  border-radius: 4px !important;
}
</style>